import { OBSERVE_REPEAT_TIME, REPORT_REPEAT_TIME, MIN_OBSERVE_TIME } from '../config.js'
import { findAllObserve, pushToObserve, activeObserve, destoryObserve } from './observe.js'
import { findAllReport, pushToReport, destoryReport } from './report.js'
import fetch from './fetch.js'

class Peach {
  constructor() {
    this.instance = null
    this.SIREPORTIME = null
    this.SIOBSERVETIME = null
  }

  initInterval() {
    // 定时器轮询
    if (!this.SIREPORTIME) {
      this.SIREPORTIME = setInterval(() => {
        // 曝光监听超时
        findAllObserve().forEach((value) => {
          const stime = new Date().getTime()
          if (stime - value.stime >= MIN_OBSERVE_TIME && !value.hasObserve) {
            pushToReport(value)
            activeObserve(value)
          } else {
            destoryObserve(value)
          }
        })
      }, OBSERVE_REPEAT_TIME)
    }

    if (!this.SIOBSERVETIME) {
      this.SIOBSERVETIME = setInterval(() => {
        // 合并上报
        const toReportList = findAllReport()
        if (toReportList.length) {
          fetch(toReportList).then(() => {
            // 上报成功清除
            toReportList.forEach(value => {
              destoryReport(value)
            })
          }).catch((err) => {
            console.log(err, 'postReportData error!')
          })
        }
      }, REPORT_REPEAT_TIME)
    }
  }

  // 单例模式
  static getInstance() {
    if (!this.instance) {
      this.instance = new Peach()
    }
    return this.instance
  }

  // 自定义上报
  logEvent(event, data = {}) {
    this.initInterval()
    pushToObserve({ type: event, data: JSON.stringify(data)})
  }

  // 页面上报
  logPage(data = {}) {
    this.initInterval()
    pushToObserve({ type: 'pagepv', data: JSON.stringify(data) })
  }
}

export default Peach
